package com.bw.lib_storage.db

import android.content.Context
import androidx.room.Room
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import net.sqlcipher.database.SupportFactory

object DBUtils {
    private lateinit var db: AppDataBase


    /**
     * 初始化数据库
     */
    fun init(context: Context, dbName: String){
        //版本升级 1_2:新增时间字段
        val MIGRATION_1_2 = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("ALTER TABLE history ADD COLUMN query_time INTEGER NOT NULL DEFAULT 0")
            }
        }
        //版本升级 2_3:新增时间字段
        val MIGRATION_2_3 = object : Migration(2, 3) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("ALTER TABLE history ADD COLUMN type TEXT NOT NULL DEFAULT 'unknown'")
            }
        }
        db = Room.databaseBuilder(context, AppDataBase::class.java, dbName)
            .allowMainThreadQueries()//允许主线程中执行查询  不规范
            .openHelperFactory(SupportFactory("123456".toByteArray()))//数据库加密
            .addMigrations(MIGRATION_1_2)
            .addMigrations(MIGRATION_2_3)
            .build()
    }

    /**
     * 获得数据库
     */
    fun getDB(): AppDataBase{
        if (db == null){
            throw NullPointerException("请先初始化数据库")
        }
        return db
    }
}